package com.zixuan.gulicollege.service_order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zixuan.gulicollege.entity.order.Order;
import com.zixuan.gulicollege.entity.order.PayLog;
import com.zixuan.gulicollege.service_order.client.EduCourseClient;
import com.zixuan.gulicollege.service_order.config.AliPayConfig;
import com.zixuan.gulicollege.service_order.config.AlipayBean;
import com.zixuan.gulicollege.service_order.mapper.PayLogMapper;
import com.zixuan.gulicollege.service_order.service.OrderService;
import com.zixuan.gulicollege.service_order.service.PayLogService;
import com.zixuan.gulicollege.service_order.utils.AliPayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author zixuan
 * @since 2021-05-26
 */
@Slf4j
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    private OrderService orderService;


    @Autowired
    private EduCourseClient eduCourseClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String aliPay(Order order) throws AlipayApiException {
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(order.getOrderNo());
        alipayBean.setSubject(order.getCourseTitle());
        alipayBean.setTotal_amount(new StringBuffer().append(order.getTotalFee()));
        alipayBean.setBody(order.getCourseTitle());
        return AliPayUtils.connect(alipayBean, order);
    }

    @Override
    public String callBack(HttpServletRequest request) throws AlipayApiException {
        // 将支付宝请求信息封装到map中
        Map<String, String> params = AliPayUtils.convertRequestParamsToMap(request);
        String paramsJson = JSON.toJSONString(params);
        log.debug(paramsJson);
        // 支付宝验签
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY,
                AliPayConfig.CHARSET, AliPayConfig.SIGN_TYPE);
        // 判断验签是否成功
        if (signVerified) {
            synchronized (PayLogServiceImpl.class) {

                String orderNum = params.get("out_trade_no");

                // 修改订单状态
                boolean orderStatus = orderService.updateOrderStatus(params);

                // 生成付款信息
                boolean insertPayInfo = insertPayInfo(params, paramsJson);

                String courseId = getOrderNumByCourseId(orderNum);
                redisTemplate.opsForValue().increment(courseId + "buy_count");

//                eduCourseClient.updateCourseBuyCount(courseId);

                return "success";
            }
        } else {
            return "failure";
        }
    }

    public String getOrderNumByCourseId(String orderNum) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNum);
        Order order = orderService.getOne(wrapper);
        return order.getCourseId();
    }

    /**
     * 生成付款信息
     *
     * @param params
     * @param paramsJson
     * @return
     */
    public boolean insertPayInfo(Map<String, String> params, String paramsJson) {
        try {

            // 获取订单号修改订单信息
            String orderNum = params.get("out_trade_no");
            // 获取支付宝交易号
            String tradeNo = params.get("trade_no");
            // 获取交易付款时间
            String gmtPayment = params.get("gmt_payment");
            // 获取支付宝实收金额
            String receiptAmount = params.get("receipt_amount");

            // 生成付款信息
            PayLog payLog = new PayLog();
            // 存储订单号
            payLog.setOrderNo(orderNum);
            // 存储交易付款时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date newDate = sdf.parse(gmtPayment);

            payLog.setPayTime(newDate);
            // 存储收款金额
            payLog.setTotalFee(new BigDecimal(receiptAmount));
            // 存储支付宝交易号
            payLog.setTransactionId(tradeNo);
            // 存储交易状态
            payLog.setTradeState("SUCCESS");
            // 存储交易方式
            payLog.setPayType(2);
            // 存储验签Json
            payLog.setAttr(paramsJson);
            return baseMapper.insert(payLog) >= 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
